package com.btex.app;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.btex.app.entity.OTCBankInfo;
import com.btex.app.entity.OTCProvincesInfo;
import com.btex.app.tools.CookieTool;
import com.btex.app.tools.MicroAVLIDialog;
import com.btex.app.tools.SharedPreferencesUtil;
import com.btex.app.tools.Util;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.PreferencesCookieStore;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class OTCAddBankActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.tv_menu)
    TextView mTvMenu;
    @BindView(R.id.rl_title)
    RelativeLayout mRlTitle;
    @BindView(R.id.otc_activity_bank_add_name)
    EditText mOtcActivityBankAddName;
    @BindView(R.id.otc_activity_bank_add_zhanghao)
    EditText mOtcActivityBankAddZhanghao;
    @BindView(R.id.otc_activity_bank_add_bank)
    EditText mOtcActivityBankAddBank;
    @BindView(R.id.otc_activity_bank_add_cities)
    EditText mOtcActivityBankAddCities;
    @BindView(R.id.otc_activity_bank_add_password)
    EditText mOtcActivityBankAddPassword;
    @BindView(R.id.otc_activity_bank_sure)
    TextView mOtcActivityBankSure;
    @BindView(R.id.otc_activity_bank_add_yinghang)
    Spinner mOtcActivityBankAddYinghang;
    @BindView(R.id.otc_activity_bank_add_shenshi)
    Spinner mOtcActivityBankAddShenshi;
    @BindView(R.id.otc_activity_bank_add_shenshi_two)
    Spinner mOtcActivityBankAddShenshiTwo;
    @BindView(R.id.otc_activity_bank_add_zhihang)
    Spinner mOtcActivityBankAddZhihang;
    private String mSelectedItem;
    private OTCProvincesInfo mOtcProvincesInfo;
    private List<OTCProvincesInfo.DataBean> mData;
    private String mId1;
    private List<OTCProvincesInfo.DataBean> mData1;
    private String mString;
    private MicroAVLIDialog mMicroAVLIDialog;
    private String parentSelectedItem;
    private String city;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_otcadd_bank);
        ButterKnife.bind(this);
        mTvTitle.setText("添加银行卡");

        mMicroAVLIDialog = new MicroAVLIDialog(this);
        initAddBank();
        initAddProvinces();

        initListener();
    }

    private void initAddProvinces() {

        final ArrayList<String> strings = new ArrayList<>();

        RequestParams params = new RequestParams();
        int num = (int) ((Math.random() * 9 + 1) * 100000);


        OkGo.<String>get(Config.GET_ALL_PROVINCE + "?rnd=" + String.valueOf(num)).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String result = response.body();

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.getString(Config.KEY_CODE).equals("1")) {

                        Gson gson = new Gson();
                        mOtcProvincesInfo = gson.fromJson(result, OTCProvincesInfo.class);
                        mData = mOtcProvincesInfo.getData();
                        String id = mOtcProvincesInfo.getData().get(1).getId();
                        for (int i = 0; i < mData.size(); i++) {
                            String val = mData.get(i).getVal();
                            strings.add(val);
                        }

                        String[] Provincesdata = strings.toArray(new String[mData.size()]);
                        //将可选内容与ArrayAdapter连接起来
                        ArrayAdapter<String> adapter = new ArrayAdapter<>(OTCAddBankActivity.this, R.layout.my_spinner, Provincesdata);
                        //设置下拉列表的风格
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        //将adapter 添加到spinner中
                        mOtcActivityBankAddShenshi.setAdapter(adapter);


                    }
                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }
        });

//
//        HttpHandler<String> send = new HttpUtils().send(HttpRequest.HttpMethod.GET, Config.GET_ALL_PROVINCE + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//                String result = responseInfo.result;
//
//                try {
//                    JSONObject jsonObject = new JSONObject(result);
//                    if (jsonObject.getString(Config.KEY_CODE).equals("1")) {
//
//                        Gson gson = new Gson();
//                        mOtcProvincesInfo = gson.fromJson(result, OTCProvincesInfo.class);
//                        mData = mOtcProvincesInfo.getData();
//                        String id = mOtcProvincesInfo.getData().get(1).getId();
//                        for (int i = 0; i < mData.size(); i++) {
//                            String val = mData.get(i).getVal();
//                            strings.add(val);
//                        }
//
//                        String[] Provincesdata = strings.toArray(new String[mData.size()]);
//                        //将可选内容与ArrayAdapter连接起来
//                        ArrayAdapter<String> adapter = new ArrayAdapter<>(OTCAddBankActivity.this, R.layout.my_spinner, Provincesdata);
//                        //设置下拉列表的风格
//                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//                        //将adapter 添加到spinner中
//                        mOtcActivityBankAddShenshi.setAdapter(adapter);
//
//
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//
//                }
//
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//
//                Toast.makeText(cxt, msg, Toast.LENGTH_SHORT).show();
//
//            }
//        });


    }

    private void initListener() {
        mOtcActivityBankAddYinghang.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                mSelectedItem = (String) parent.getSelectedItem();


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        mOtcActivityBankAddShenshi.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                parentSelectedItem = (String) parent.getSelectedItem();

                mId1 = mData.get(position).getId();
                getCity(mId1);

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        mOtcActivityBankAddShenshiTwo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                city = (String) parent.getSelectedItem();

                mString = mData1.get(position).getId();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void getCity(String id1) {


        RequestParams params = new RequestParams();
        params.addQueryStringParameter("province_id", id1);
        int num = (int) ((Math.random() * 9 + 1) * 100000);
        final ArrayList<String> strings = new ArrayList<>();

        OkGo.<String>get(Config.GET_CITYS + "?rnd=" + String.valueOf(num)).params("province_id", id1).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String result = response.body();

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.getString(Config.KEY_CODE).equals("1")) {
                        Gson gson = new Gson();
                        mOtcProvincesInfo = gson.fromJson(result, OTCProvincesInfo.class);
                        mData1 = mOtcProvincesInfo.getData();
                        for (int i = 0; i < mData1.size(); i++) {
                            String val = mData1.get(i).getVal();
                            strings.add(val);
                        }

                        String[] Provincesdata = strings.toArray(new String[mData1.size()]);
                        //将可选内容与ArrayAdapter连接起来
                        ArrayAdapter<String> adapter = new ArrayAdapter<>(OTCAddBankActivity.this, R.layout.my_spinner, Provincesdata);
                        //设置下拉列表的风格
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        //将adapter 添加到spinner中
                        mOtcActivityBankAddShenshiTwo.setAdapter(adapter);

                    }
                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }
        });
//
//        HttpHandler<String> send = new HttpUtils().send(HttpRequest.HttpMethod.GET, Config.GET_CITYS + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//                String result = responseInfo.result;
//
//                try {
//                    JSONObject jsonObject = new JSONObject(result);
//                    if (jsonObject.getString(Config.KEY_CODE).equals("1")) {
//                        Gson gson = new Gson();
//                        mOtcProvincesInfo = gson.fromJson(result, OTCProvincesInfo.class);
//                        mData1 = mOtcProvincesInfo.getData();
//                        for (int i = 0; i < mData1.size(); i++) {
//                            String val = mData1.get(i).getVal();
//                            strings.add(val);
//                        }
//
//                        String[] Provincesdata = strings.toArray(new String[mData1.size()]);
//                        //将可选内容与ArrayAdapter连接起来
//                        ArrayAdapter<String> adapter = new ArrayAdapter<>(OTCAddBankActivity.this, R.layout.my_spinner, Provincesdata);
//                        //设置下拉列表的风格
//                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//                        //将adapter 添加到spinner中
//                        mOtcActivityBankAddShenshiTwo.setAdapter(adapter);
//
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//
//                }
//
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//
//                Toast.makeText(cxt, msg, Toast.LENGTH_SHORT).show();
//
//            }
//        });

    }


    private void initAddBank() {
        RequestParams params = new RequestParams();
        int num = (int) ((Math.random() * 9 + 1) * 100000);


        OkGo.<String>get(Config.GET_BANKS + "?rnd=" + String.valueOf(num)).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String result = response.body();
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.getString(Config.KEY_CODE).equals("1")) {
                        Gson gson = new Gson();
                        OTCBankInfo otcProvincesInfo = gson.fromJson(result, OTCBankInfo.class);
                        List<String> data = otcProvincesInfo.getData();
                        String[] strings = data.toArray(new String[data.size()]);
//                        //将可选内容与ArrayAdapter连接起来
                        ArrayAdapter<String> adapter = new ArrayAdapter<>(OTCAddBankActivity.this, R.layout.my_spinner, strings);
                        //设置下拉列表的风格
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        //将adapter 添加到spinner中
                        mOtcActivityBankAddYinghang.setAdapter(adapter);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }
        });

//        HttpHandler<String> send = new HttpUtils().send(HttpRequest.HttpMethod.GET, Config.GET_BANKS + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//                String result = responseInfo.result;
//                try {
//                    JSONObject jsonObject = new JSONObject(result);
//                    if (jsonObject.getString(Config.KEY_CODE).equals("1")) {
//                        Gson gson = new Gson();
//                        OTCBankInfo otcProvincesInfo = gson.fromJson(result, OTCBankInfo.class);
//                        List<String> data = otcProvincesInfo.getData();
//                        String[] strings = data.toArray(new String[data.size()]);
////                        //将可选内容与ArrayAdapter连接起来
//                        ArrayAdapter<String> adapter = new ArrayAdapter<>(OTCAddBankActivity.this, R.layout.my_spinner, strings);
//                        //设置下拉列表的风格
//                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//                        //将adapter 添加到spinner中
//                        mOtcActivityBankAddYinghang.setAdapter(adapter);
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//
//                }
//
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//
//                Toast.makeText(cxt, msg, Toast.LENGTH_SHORT).show();
//
//            }
//        });
    }


    @Override
    public void setData() {

    }

    @Override
    public void onClick(View v) {

    }

    @OnClick({R.id.iv_back, R.id.otc_activity_bank_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.otc_activity_bank_sure:


                if (TextUtils.isEmpty(mSelectedItem)) {
//                    SnackbarShow("开户银行不能为空");
                    Util.showSnachBar(OTCAddBankActivity.this, getResources().getColor(R.color.red), "开户银行不能为空");
                    return;
                }

                if (TextUtils.isEmpty(parentSelectedItem)) {
//                    SnackbarShow("开户省份不能为空");
                    Util.showSnachBar(OTCAddBankActivity.this, getResources().getColor(R.color.red), "开户省份不能为空");

                    return;
                }

                if (TextUtils.isEmpty(city)) {
//                    SnackbarShow("开户城市不能为空");
                    Util.showSnachBar(OTCAddBankActivity.this, getResources().getColor(R.color.red), "开户城市不能为空");
                    return;
                }


                if (TextUtils.isEmpty(mOtcActivityBankAddCities.getText().toString().trim())) {
//                    SnackbarShow("开户支行不能为空");
                    Util.showSnachBar(OTCAddBankActivity.this, getResources().getColor(R.color.red),"开户支行不能为空");
                    return;
                }

                if (TextUtils.isEmpty(mOtcActivityBankAddName.getText().toString().trim())) {
                    Util.showSnachBar(OTCAddBankActivity.this, getResources().getColor(R.color.red),"姓名不能为空");
//                    SnackbarShow("姓名不能为空");
                    return;
                }

                if (TextUtils.isEmpty(mOtcActivityBankAddZhanghao.getText().toString().trim())) {
//                    SnackbarShow("账号不能为空");
                    Util.showSnachBar(OTCAddBankActivity.this, getResources().getColor(R.color.red),"账号不能为空");
                    return;
                }


                if (TextUtils.isEmpty(mOtcActivityBankAddPassword.getText().toString().trim())) {
//                    SnackbarShow("密码不能为空");
                    Util.showSnachBar(OTCAddBankActivity.this, getResources().getColor(R.color.red),"密码不能为空");
                    return;
                }


                setOtcData();

                break;
        }
    }

    private void setOtcData() {
        mMicroAVLIDialog.show();
        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(this, SharedPreferencesUtil.getSharedPreferences(this));
        RequestParams params = new RequestParams();
//        params.addBodyParameter("type", "bank");
//        params.addBodyParameter("card_no", mOtcActivityBankAddZhanghao.getText().toString().trim());
//        params.addBodyParameter("trade_psw", mOtcActivityBankAddPassword.getText().toString().trim());
//        params.addBodyParameter("bank_branch", mOtcActivityBankAddCities.getText().toString().trim());
//        params.addBodyParameter("bank", mSelectedItem);
//        params.addBodyParameter("city_id", mString);
//        params.addBodyParameter("province_id", mId1);


        HashMap<String, String> stringStringHashMap = new HashMap<>();

        stringStringHashMap.put("type", "bank");
        stringStringHashMap.put("card_no", mOtcActivityBankAddZhanghao.getText().toString().trim());
        stringStringHashMap.put("trade_psw", mOtcActivityBankAddPassword.getText().toString().trim());
        stringStringHashMap.put("bank_branch", mOtcActivityBankAddCities.getText().toString().trim());
        stringStringHashMap.put("bank", mSelectedItem);
        stringStringHashMap.put("city_id", mString);
        stringStringHashMap.put("province_id", mId1);
        OkGo.<String>post(Config.SET_PAY_CARD).params(stringStringHashMap).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                mMicroAVLIDialog.dismiss();
                String result = response.body();
                try {
                    JSONObject jsonObject = new JSONObject(result);
//                    SnackbarShow(jsonObject.getString("info"));
                    Util.showSnachBar(OTCAddBankActivity.this, getResources().getColor(R.color.red),jsonObject.getString("info"));
                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }
        });

//        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.POST, Config.SET_PAY_CARD, params, new RequestCallBack<String>() {
//
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//
//
//                mMicroAVLIDialog.dismiss();
//                String result = responseInfo.result;
//                try {
//                    JSONObject jsonObject = new JSONObject(result);
////                    SnackbarShow(jsonObject.getString("info"));
//                    Util.showSnachBar(OTCAddBankActivity.this, getResources().getColor(R.color.red),jsonObject.getString("info"));
//                } catch (JSONException e) {
//                    e.printStackTrace();
//
//                }
//
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//
//
//            }
//
//            @Override
//            public void onLoading(long total, long current, boolean isUploading) {
//                super.onLoading(total, current, isUploading);
//
//            }
//        });
    }

//    private void SnackbarShow(String ms) {
//
//        Snackbar snackbar = ShortSnackbar(mOtcActivityBankAddName, ms, Color.parseColor("#ffffff"), Color.parseColor("#272736"));
//        snackbar.show();
//    }
//
//    public static Snackbar ShortSnackbar(View view, String message, int messageColor, int backgroundColor) {
//        Snackbar snackbar = Snackbar.make(view, message, Snackbar.LENGTH_SHORT);
//        setSnackbarColor(snackbar, messageColor, backgroundColor);
//        return snackbar;
//    }

    /**
     * 设置Snackbar文字和背景颜色
     *
     * @param snackbar
     * @param messageColor
     * @param backgroundColor
     */
//    public static void setSnackbarColor(Snackbar snackbar, int messageColor, int backgroundColor) {
//        View view = snackbar.getView();
//
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
//            TextView message = (TextView) snackbar.getView().findViewById(R.id.snackbar_text);
//            //View.setTextAlignment需要SDK>=17
//            message.setTextAlignment(View.TEXT_ALIGNMENT_GRAVITY);
//            message.setGravity(Gravity.CENTER);
//        }
//
//        if (view != null) {
//            view.setBackgroundColor(backgroundColor);
//            ((TextView) view.findViewById(R.id.snackbar_text)).setTextColor(messageColor);
//        }
//    }


}
